const VideoCenter = require("../model/videoCenter");

module.exports = {
  // 获取列表
  videoCenter_list: async (req, res) => {
    const { page, limit } = req.query;
    const offset = (page - 1) * limit;
    try {
      const informationList = await VideoCenter.findAndCountAll({
        offset,
        limit,
        order: [["create_time", "DESC"]],
      });
      res.json({ code: 1, message: "获取资料列表成功", data: informationList });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 添加
  videoCenter_add: async (req, res) => {
    const { title, cover_url, video_url } = req.body;
    try {
      // 先查询是否存在
      if (await VideoCenter.findOne({ where: { title } })) {
        return res.json({ code: -1, message: "视频名称已存在" });
      }
      const information = await VideoCenter.create({
        title: title,
        cover: cover_url,
        video_url: video_url,
      });
      if (!information) {
        return res.json({ code: -1, message: "添加资料失败" });
      }
      res.json({ code: 1, message: "添加资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 修改
  videoCenter_update: async (req, res) => {
    const { video_id, title, cover_url } = req.body;
    try {
      // 先查询是否存在
      const record = await VideoCenter.findByPk(video_id);
      if (!record) {
        return res.json({ code: -1, message: "资料不存在" });
      }
      if (record.file_name === title) {
        return res.json({ code: 1, message: "修改资料成功" });
      }
      if (await VideoCenter.findOne({ where: { title } })) {
        return res.json({ code: -1, message: "资料名称已存在" });
      }
      const row = await VideoCenter.update({ title, cover: cover_url }, { where: { video_id } });
      if (!row) {
        return res.json({ code: -1, message: "修改资料失败" });
      }
      res.json({ code: 1, message: "修改资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 删除
  videoCenter_delete: async (req, res) => {
    const { video_id } = req.query;
    try {
      // 先查询是否存在
      const record = await VideoCenter.findByPk(video_id);
      if (!record) {
        return res.json({ code: -1, message: "资料不存在" });
      }
      const row = await VideoCenter.destroy({ where: { video_id } });
      if (!row) {
        return res.json({ code: -1, message: "删除资料失败" });
      }
      res.json({ code: 1, message: "删除资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
};
